<template>
  <div class="carnbon-container">

    <el-breadcrumb separator="/" style="padding:20px 20px 10px">
      <el-breadcrumb-item>基础信息</el-breadcrumb-item>
      <el-breadcrumb-item :to="'/carbon/product'">能碳产品管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="'/carbon/product/detail'">详情</el-breadcrumb-item>
    </el-breadcrumb>

    <div style="padding:20px 20px 0 20px;">
    <el-descriptions direction="vertical" :column="8" border>
      <el-descriptions-item label="主体">{{tableInfo.project.name}}</el-descriptions-item>
      <el-descriptions-item label="	产品名称">{{tableInfo.name}}</el-descriptions-item>
      <el-descriptions-item label="产品单价">{{tableInfo.price}}</el-descriptions-item>
      <el-descriptions-item label="	产品单位">{{tableInfo.unit}}</el-descriptions-item>
      <el-descriptions-item label="	预计产品产出">{{tableInfo.totalPlanOutput || '--'}}</el-descriptions-item>
      <el-descriptions-item label="	产品产出">{{tableInfo.totalActualOutput || '--'}}</el-descriptions-item>
      <el-descriptions-item label="	产品描述">{{tableInfo.description}}</el-descriptions-item>
    </el-descriptions>
    </div>

    <div class="search-form">
      <el-form inline :model="searchFromData">
        <el-form-item label="年度" prop="yearValue">
          <el-date-picker v-model="searchFromData.yearValue" type="year" placeholder="请选择一个年份" @change="handlerPicker"/>
        </el-form-item>
        <el-button @click="onReset">清除</el-button>
        <el-button class="saveBtn" type="primary" @click="onSearchClicked">查询</el-button>
        <span class="form-tips" style="margin-left: 50px">全年预计产品产出：269 kwh</span>
        <span class="form-tips">全年产品产出：270 kwh</span>
        <span style="float: right;margin-right: 20px;line-height: 28px;margin-top:1px;"><span class="blue-point"></span>已填写</span>
      </el-form>
    </div>

    <div class="monthCalender-box" v-if="dom">
      <monthCalendar :yearNumber="yearValue" :monthNumber="1" ></monthCalendar>
      <monthCalendar :yearNumber="yearValue" :monthNumber="2" ></monthCalendar>
      <monthCalendar :yearNumber="yearValue" :monthNumber="3" ></monthCalendar>
      <monthCalendar :yearNumber="yearValue" :monthNumber="4" ></monthCalendar>
      <monthCalendar :yearNumber="yearValue" :monthNumber="5" ></monthCalendar>
      <monthCalendar :yearNumber="yearValue" :monthNumber="6" ></monthCalendar>
      <monthCalendar :yearNumber="yearValue" :monthNumber="7" ></monthCalendar>
      <monthCalendar :yearNumber="yearValue" :monthNumber="8" ></monthCalendar>
      <monthCalendar :yearNumber="yearValue" :monthNumber="9" ></monthCalendar>
      <monthCalendar :yearNumber="yearValue" :monthNumber="10" ></monthCalendar>
      <monthCalendar :yearNumber="yearValue" :monthNumber="11" ></monthCalendar>
      <monthCalendar :yearNumber="yearValue" :monthNumber="12" ></monthCalendar>
    </div>


  </div>
</template>
<script setup lang="ts">
  import { appAuthList, appBacthPass, appDeny, appPass } from '@/ajax/index';
  import CustomTableTwo from '@/components/CustomTableTwo.vue';
  import { dateFormat, FormatsEnums } from '@/utils/dateUtil';
  import { getCurrentInstance, ref, nextTick } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import addProduct from './addProduct.vue'
  import monthCalendar from './components/monthCalendar.vue'

  const { ctx , proxy } = getCurrentInstance() as any;
  const activeName = ref('authApply')
  const checkedRows = ref([])

  let router = useRouter()
  let route = useRoute();


  let dom = ref(true)
  let tableData = [
    {"id":7,"name":"产值","projectId":1,"project":{"id":1,"name":"周口市中医院"},"unit":"kwh","description":null,"totalPlanOutput":null,"totalActualOutput":null,"price":34},
    {"id":7,"name":"产值","projectId":1,"project":{"id":1,"name":"周口市中医院"},"unit":"kwh","description":null,"totalPlanOutput":null,"totalActualOutput":null,"price":34},
    {"id":6,"name":"产值1","projectId":1,"project":{"id":1,"name":"周口市中医院"},"unit":"52","description":"lyj","totalPlanOutput":null,"totalActualOutput":null,"price":520},{"id":5,"name":"产值C","projectId":1,"project":{"id":1,"name":"周口市中医院"},"unit":"kg","description":"产值C","totalPlanOutput":null,"totalActualOutput":null,"price":58.7},{"id":4,"name":"产值B","projectId":1,"project":{"id":1,"name":"周口市中医院"},"unit":"kg","description":"产值B","totalPlanOutput":null,"totalActualOutput":null,"price":65.2},{"id":3,"name":"A类油","projectId":1,"project":{"id":1,"name":"周口市中医院"},"unit":"kg","description":"润滑油工厂-A类油","totalPlanOutput":null,"totalActualOutput":null,"price":75.8},{"id":2,"name":"机组#1-产电","projectId":1,"project":{"id":1,"name":"周口市中医院"},"unit":"MWh","description":"润滑油工厂-产电","totalPlanOutput":null,"totalActualOutput":null,"price":45.6},{"id":1,"name":"机组#1-产热","projectId":1,"project":{"id":1,"name":"周口市中医院"},"unit":"GJ","description":"润滑油工厂-产热","totalPlanOutput":null,"totalActualOutput":null,"price":46.5}
  ];
  console.log('router',route.query.id);
  let id = 7- ~~(route.query.id)
  let tableInfo = tableData[id]

  console.log(tableInfo);
  const tableConfig = ref({})
  const isRefresh = ref(false)

  const searchFromData = ref({
    yearValue:new Date(),
  })

  let yearValue = ref(new Date().getFullYear())
  let newYear = new Date().getFullYear();

  const handlerPicker = (year)=>{
    dom.value = false
    yearValue.value = year.getFullYear()
    nextTick(()=>{
      dom.value = true
    })
  }
  //type：0-全部授权 1-授权通过
  const submit = (type: number, data: any) => {
    const msgLabel = {
      0: "全部授权通过",
      1: "通过"
    }
    ElMessageBox.confirm(
      `确定要${msgLabel[type]}吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(async () => {
      let res = {
        succ: false
      }
      if (type == 0) {
        res = await appBacthPass({})
      }
      if (type == 1) {
        res = await appPass({id: data.id})
      }
      if (res.succ) {
        ElMessage({
          type: 'success',
          message: '操作成功',
        })
        isRefresh.value = true
        nextTick(()=>{
          isRefresh.value = false
        })
      }
    }).catch(() => {
      ElMessage({
        type: 'info',
        message: '您已取消操作',
      })
    })
  }

  const areaFormRef = ref(null)
  const openAddProduct = () => {
    console.log(areaFormRef.value);
    console.log(ctx.$refs.areaFormRef);
    areaFormRef.value && areaFormRef.value.open();
  }


  //批量通过
  const batchToAuthPass = () => {
    const ids = []

    checkedRows.value.forEach((item:any) => {
      ids.push(item.id)
    });
    submit(0, checkedRows)
  }
  //单条通过
  const authPass = (row: any) => {
    submit(1, row)
  }
  const authRef = ref()
  //单条拒绝
  const onSearchClicked = (row: any) => {
    const info = {
      id: row.id,
      audit_comment: ''
    }
    authRef.value.init(info)
  }
  const handleAuthDeny = async (data: any) => {
    const res = await appDeny(data.value)
    if (res.succ) {
      ElMessage({
        type: 'success',
        message: '操作成功'
      })
      authRef.value.handleClose()
      isRefresh.value = true
      nextTick(()=>{
        isRefresh.value = false
      })
    }
  }
  //多选框勾选回调
  const selectionChange = (checked: any) => {
    checkedRows.value = checked
  }

  const onReset = (row: any) => {
  }

  const go = (path: string) => {
    router.push({
      name:path
    })
  }

  const statusMap = {
    approved: "已通过",
    declined: "已驳回",
    // requesting: "请求中",
  }
  tableConfig.value = {
    // 表格顶部的操作按钮
    'actionBtns': [
      {
        'type': `primary`, // 按钮类型
        'icon': `Plus`, // 按钮上的图标
        label: `增加产品`, // 按钮展示的文字
        'isRefresh': true, // 执行完事件是否刷新页面
        'btnCallback': openAddProduct // 事件回调
      },
      {
        'type': `primary`, // 按钮类型
        'icon': `Plus`, // 按钮上的图标
        label: `增加产量`, // 按钮展示的文字
        'isRefresh': false, // 执行完事件是否刷新页面
        'btnCallback': batchToAuthPass // 事件回调
      }
    ],
    // 是否隐藏序号列
    'isHiddenIndex': {
      'type': false,
      'required': false,
      'default': false
    },
    'isRefresh': false,
    // 表格展示配置
    'tableHeader': [
      {
        label: '主体',		// 是否隐藏序号列
        prop: 'project.name',
        innerHTML: (row: any) => {
          return `<span>${row.project?.name}</span>`
        }
      },
      {
        label: '产品名称',
        prop: 'name',
        width:'300px'
      },
      {
        label: '产品单价(元)',
        prop: 'price',
        width:'160px'
      },
      {
        label: '	产品单位',
        prop: 'unit',
        width:'160px'
      },
      {
        label: '	产品描述',
        prop: 'description',
      },
      {
        label: '操作',
        prop: 'id',
        fixed:  'right',
        btns: [
          {
            label: '编辑',
            btnCallback: () => {}
          },
          {
            label: '详情',
            btnCallback: () => {}
          },
          {
            label: '关联算法',
            btnCallback: () => {
              //openFormula(row)
            }
          },
          {
            label: '删除',
            btnCallback: () => {
              ElMessageBox.confirm(
                `确定要删除吗？`,
                '提示',
                {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning',
                }
              ).then(async () => {
                let res = {
                  succ: false
                }
                if (type == 0) {
                  res = await appBacthPass({})
                }
                if (type == 1) {
                  res = await appPass({id: data.id})
                }
                if (res.succ) {
                  ElMessage({
                    type: 'success',
                    message: '操作成功',
                  })
                  isRefresh.value = true
                  nextTick(()=>{
                    isRefresh.value = false
                  })
                }
              }).catch(() => {
                ElMessage({
                  type: 'info',
                  message: '您已取消操作',
                })
              })
            }
          }
        ],
        width:'300px'
      },
    ],

  }
  const operatorMap = {
    all: "全部"
  }

  const searchCallback = async () => {
    const params = {
      pageNumber:1,
      pageSize:1000
    }
    try {
      const res = await appAuthList(params)
      let list = res.content.data.requests || []
      console.log('list',list);
      if (!res.succ) {
        return
      }
      list = [
        {"id":7,"name":"产值","projectId":1,"project":{"id":1,"name":"周口市中医院"},"unit":"kwh","description":null,"totalPlanOutput":null,"totalActualOutput":null,"price":34},
        {"id":6,"name":"产值1","projectId":1,"project":{"id":1,"name":"周口市中医院"},"unit":"52","description":"lyj","totalPlanOutput":null,"totalActualOutput":null,"price":520},{"id":5,"name":"产值C","projectId":1,"project":{"id":1,"name":"周口市中医院"},"unit":"kg","description":"产值C","totalPlanOutput":null,"totalActualOutput":null,"price":58.7},{"id":4,"name":"产值B","projectId":1,"project":{"id":1,"name":"周口市中医院"},"unit":"kg","description":"产值B","totalPlanOutput":null,"totalActualOutput":null,"price":65.2},{"id":3,"name":"A类油","projectId":1,"project":{"id":1,"name":"周口市中医院"},"unit":"kg","description":"润滑油工厂-A类油","totalPlanOutput":null,"totalActualOutput":null,"price":75.8},{"id":2,"name":"机组#1-产电","projectId":1,"project":{"id":1,"name":"周口市中医院"},"unit":"MWh","description":"润滑油工厂-产电","totalPlanOutput":null,"totalActualOutput":null,"price":45.6},{"id":1,"name":"机组#1-产热","projectId":1,"project":{"id":1,"name":"周口市中医院"},"unit":"GJ","description":"润滑油工厂-产热","totalPlanOutput":null,"totalActualOutput":null,"price":46.5}];
      for (let index = 0; index < list.length; index++) {
        const element = list[index];
        list[index].request_time_text = dateFormat(element.request_time, FormatsEnums.YMDHI)
        list[index].operator_text = operatorMap[element.operator] || ''
        list[index].is_copyable_text = element.is_copyable ? '是' : '否'
      }
      return {
        "success": true,
        "message": "string",
        "content": {
          "size": 10,
          "records": list,
          "current": 0,
          "pages": 1,
          "total": 7
        }
      }
    } catch (error) {
      console.log("error", error)
    }

    // return {
    //     "success": true,
    //     "message": "string",
    //     "content": {
    //         "size": 0,
    //         "records": tableData,
    //         "current": 0,
    //         "pages": 0,
    //         "total": 0
    //     },
    //     "options": {
    //         "additionalProp1": {},
    //         "additionalProp2": {},
    //         "additionalProp3": {}
    //     }
    // }
  }

  const created = () => {

  }

</script>
<style lang="scss" scoped>
  .monthCalender-box{
    padding: 9px;
  }
  .blue-point{
    display: inline-block;
    width: 8px;
    height: 8px;
    margin-right: 10px;
    background-color: #12c4dc;
    border-radius: 2px;
  }
  .form-tips{
    display: inline-block;
    vertical-align: top;
    line-height: 26px;
    margin-right: 10px;
    margin-left: 10px;
  }
</style>